local BaseData = require("data.base.BaseData")
local ChatData = class("ChatData", BaseData)
local ChatMsgData = require("data.ChatMsgData")

local MSG_MAX_CACHE = 200
local MAX_ALL_MSg = 20

local schema = {}
ChatData.schema = schema

function ChatData:ctor()
    ChatData.super.ctor(self)
    self._chatUsers = {}
    self._chatMsgs = {}
    self._allChatMsgs = {}
    self._signalChat = G_NetWorkManager:add(MessageIDConst.ID_S2C_Chat, handler(self, self._s2cChat))
end

function ChatData:clear()
    self._signalChat:remove()
    self._signalChat = nil
end

function ChatData:getMsgList(playerId)
    return self._chatMsgs[playerId] or {}
end

function ChatData:getChatList(userId)
    local result = {}
    for id, name in pairs(self._chatUsers) do
        if id ~= userId then
            local param = {}
            param.userId = id
            param.name = name
            table.insert(result, param)
        end
    end
    return result
end

function ChatData:c2sChat(receiveId, content)
    G_NetWorkManager:send(
        MessageIDConst.ID_C2S_Chat,
        {
            receiveId = receiveId,
            content = content
        }
    )
end

function ChatData:getAllChatMsgs()
    return self._allChatMsgs
end

function ChatData:_s2cChat(id, message)
    local msg = ChatMsgData.new()
    msg:update(message)
    local playerId = msg:getPlayerId()
    self._chatUsers[playerId] = msg:getThe_name()
    if not self._chatMsgs[playerId] then
        self._chatMsgs[playerId] = {}
    end
    local count = #self._chatMsgs[playerId]
    if count == MSG_MAX_CACHE then
        table.remove(self._chatMsgs[playerId], count)
    end
    table.insert(self._chatMsgs[playerId], 1, msg)
    local countAll = #self._allChatMsgs
    if countAll == MAX_ALL_MSg then
        table.rmeove(self._allChatMsgs, countAll)
    end
    table.insert(self._allChatMsgs, 1, msg)
    G_SignalManager:dispatch(SignalConst.EVENT_CHAT_MSG_UPDATE, msg)
end

return ChatData
